if not menu then menu = {} end

if not menu.chart then


menu.chart = {
	changed = {},
	charts = {}
}


processor:AddInit(function()
	window:AddRow()
	menu.chart.row = window:AddRow()
	window:AddRow()
	menu.chart.rows = 2
	
	menu.chart.chart = {
		index = 1,
		col = 1,
		row = 0,
		b_color = QTABLE_DEFAULT_COLOR,
		f_color = QTABLE_DEFAULT_COLOR
	}
end)


processor:AddHandler("OnTableNotification", function(data)
	if data.msg == 11 and data.par1 >= menu.chart.row
		and data.par1 < menu.chart.row + menu.chart.rows
	then
		menu.chart:Select(data.par1 - menu.chart.row + 1, data.par2)
	end
end)


processor:AddTimer(function()
	local pos = orders:GetPosition(nil, true)
	local str = lib:toline(pos)
	if menu.chart.last_pos ~= str then
		menu.chart.last_pos = str
		
		local r, cols = window:size()
		local charts = {}
		local i = 0
		
		for k, v in pairs(pos) do
			i = i + 1
			r = (i + 1 - (i % cols + 1)) / cols
			if r < menu.chart.rows then
				table.insert(charts, k)
				if menu.chart.charts[k] then
					charts[k] = menu.chart.charts[k]
				else
					charts[k] = {
						b_color = QTABLE_DEFAULT_COLOR,
						f_color = QTABLE_DEFAULT_COLOR,
						instrument = lib:GetInstrument(k)
					}
				end
				charts[k].index = i
				charts[k].col = i % cols + 1
				charts[k].row = r
			end
		end
		
		menu.chart.charts = charts
		
		for i = 1, menu.chart.rows * cols - 1 do
			if charts[i] then
				window:SetCell(charts[charts[i]].row + menu.chart.row, charts[charts[i]].col, charts[i])
			else
				window:SetCell((i + 1 - (i % cols + 1)) / cols + menu.chart.row, i % cols + 1, "")
			end
		end
	end
end)


processor:AddTimer(function()
	menu.chart:SetChartColor(menu.chart.chart, menu.chart.instrument)
	for i, code in ipairs(menu.chart.charts) do
		menu.chart:SetChartColor(menu.chart.charts[menu.chart.charts[i]])
	end
end)


function menu.chart:SetChartColor(chart, instrument)
	instrument = instrument or chart.instrument
	if type(chart) == "table" and instrument then
		local color = QTABLE_DEFAULT_COLOR
		local pos, limits = orders:GetPosition(instrument)
		if pos > 0 then
			color = RGB(0, 128, 0)
		elseif pos < 0 then
			color = RGB(192, 0, 0)
		elseif limits ~= 0 then
			color = RGB(128, 0, 255)
		end
		
		if chart.f_color ~= color then
			chart.f_color = color
			window:SetColor(menu.chart.row + chart.row, chart.col, chart)
		end
	end
end


function menu.chart:Select(row, col)
	local index, cols = window:size()
	if col > 0 and col <= cols and row > 0 and row <= self.rows then
		index = (row - 1) * cols + col - 1
		if index > 0 and index <= #self.charts then
			lib:SaveLabels(self.charts[index])
		end
	end
end


end	-- of file
